var config = {		//测试版
    request_url:'https://appapi.superluck.top',	//请求地址
	//request_url:'http://appapi.yiyouhui.qartificialplant.com',
	request_url2:'http://appapi.wdq.kx.wenguiqin.com',	//备用地址
	share_url:'https://m.wdq.kx.wenguiqin.com/',	//分享网页地址
    appid:'20220224093248230479234',
    appsecret:'dje399lldvjxcl342mldsdjdkij92sakf23saef',
	mini_appid:'wx8b0db8e20bafb6bb'		//小程序id
};

/*
var config = {		//正式版
    //request_url:'http://appapi.bf.kx.wenguiqin.com', 
	request_url:'http://appapi.renqimofang.com', 
	img_url:'https://www.renqimofang.com', 
    appid:'201799045678934575434500',
    appsecret:'yhgfhkgjht7fhyddtjgu76ghfgn88hfn',
};*/

/*
var config = {		//正式版
    //request_url:'http://appapi.bf.kx.wenguiqin.com', 
	request_url:'http://appapi.renqimofang.com', 
	img_url:'https://www.renqimofang.com', 
    appid:'201799045678934575434500',
    appsecret:'yhgfhkgjht7fhyddtjgu76ghfgn88hfn',
};*/
var get_num = 0;
 //获取access_token
var get_access_token = function get_access_token(relFunc,n){
	get_num++;
	if(get_num >= 70){
		return false;
	}
	//console.log('get_access_token'+n);
	uni.request({
	    url: config.request_url+'/index/token/get_access_token?appid='+config.appid+'&appsecret='+config.appsecret,
	    header: {
	        'custom-header': 'hello' //自定义请求头信息
	    },
	    success: (res) => {
			res = res.data;
	        if(res.code == 200){
				uni.setStorageSync('access_token',res.data);
				var access_token = uni.getStorageSync('access_token');
	        	relFunc();
	        }else{
	        	console.log(res.msg);
	        }
	    },
		fail(){
			reset_domain();
		}
	});
}

var param_to_url = function param_to_url(id,url){
	uni.navigateTo({
		url:url
	});
}
//是否登录
var common_if_login = function common_if_login(func1,func2){
	var userInfo = uni.getStorageSync('userInfo');
	if(!userInfo){
		uni.request({
		    url: config.request_url+'/index/members/home/if_login?token=111',
		    header: {
		        'custom-header': 'hello' //自定义请求头信息
		    },
			fail(){
				reset_domain();
				
			}
		});
		func1();
	}else{
		userInfo = JSON.parse(userInfo)
		var access_token = uni.getStorageSync('access_token');		
		uni.request({
		    url: config.request_url+'/index/members/home/if_login?token='+userInfo.token,
		    header: {
		        'custom-header': 'hello' //自定义请求头信息
		    },
		    success: (res) => {
				
				res = res.data;
		        if(res.code == 200){
					//将登录信息写入缓存
					if(res.data != userInfo.level){
						userInfo.level = res.data;
						userInfo = JSON.stringify(userInfo);
						uni.setStorageSync('userInfo',userInfo);
					}
					func2();
		        }else{
					func1();
		        }
		    },
			fail(){
				reset_domain();
				
			}
		});
	}
	
}

//加载列表
var load_common_list = function load_common_list(url,that,data_name){
	
	that.page++;
	var page = that.page;
	if (that.loadingType != 0) {//loadingType!=0;直接返回
		return false;
	}
	var formData = {
		page:that.page
	}
	
	that.loadingType = 1;
	//uni.showNavigationBarLoading();
	var url = url;
	
	uni.request({
		url:url,
		data:formData,
		success:(res) => {
			res = res.data;
			console.log('sssddd'+that.page);
			if(that.page == 1){
				that[data_name] = [];
			}
			if(res.code == 200){
				that.data_empty = 0;
				if(page == 1){
					that[data_name] = res.data;
				}else{
					for(var i = 0;i < res.data.length;i++){
						that[data_name] = that[data_name].concat(res.data[i]);
					}
				}
				if(res.data.length < 16){
					that.loadingType = 2;
					uni.hideNavigationBarLoading();//关闭加载动画
					uni.stopPullDownRefresh();//得到数据后停止下拉刷新
					return false;
				}
			}else{
				if(res.code == 10027){
					uni.redirectTo({
						url:'../user/login'
					});
				}
				if(res.code == 10028){
					that.loadingType = 2;
					uni.hideNavigationBarLoading();//关闭加载动画
					uni.stopPullDownRefresh();//得到数据后停止下拉刷新
					return false;
				}
			}
			uni.hideNavigationBarLoading();//关闭加载动画
			uni.stopPullDownRefresh();//得到数据后停止下拉刷新
			that.loadingType = 0;
		}
	});
}
function reset_domain(){
	var the_url = config.request_url2;
	r = the_url.split('//');
	var r1 = r[1].split('.');
	var res = r1[0];
	var the_list = new Array('appi','aaqqi','ipappi','nsdai','insi','dnsi','nisti','stini','ttnsi','nsiii');
	var the_no = uni.getStorageSync('dno');
	the_no = (typeof the_no == 'undefined' || !the_no) ? 0 : the_no;
	var new_no = '';
	for(var i = 0;i < the_list[the_no].length;i++){
		var r = the_list[the_no][i].charCodeAt()+1;
		r = String.fromCharCode(r);
		new_no+=r;
	}
	var new_domain = the_url.replace(res,new_no+'.appapi');
	the_no = the_no >= 9 ? 0 : the_no+1;
	uni.setStorageSync('dno',the_no);
	uni.setStorageSync('request_tmp',new_domain);
	plus.runtime.restart();
}
//重置列表
function reset_list(that,func,the_key,act){
	if(typeof the_key != 'undefined' && the_key && act != 2){
		//that[the_key] = {};
	}
	that.page = 0;
	that.loadingType = 0;
	func();
}

//加载消息
function load_msg(url){
	uni.request({
	    url: url,
	    header: {
	        'custom-header': 'hello' //自定义请求头信息
	    },
	    success: (res) => { 
			res = res.data;
	        if(res.code == 200){
				if(res.data > 0){
					uni.setTabBarBadge({
					  index: 1,
					  text: '1+'
					});
				}else{
					uni.removeTabBarBadge({
					  index: 1
					});
				}
	        }
	    }
	});
}
//提示框
function calert(msg){
	uni.showModal({
		title:'友情提示',
		content:msg,
		confirmColor:'#ff0000',//删除字体的颜色
		showCancel:false
	})
}

//图片上传
function upload_file(that,up_count,url,the_key){
	uni.chooseImage({
		count: up_count,
		sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
		sourceType: ['album'], //从相册选择
		success: function (res){
			uni.showLoading({
				title:'正在上传',
			});
			const tempFilePaths = res.tempFilePaths;
			const uploadTask = uni.uploadFile({
				url : url,
				filePath: tempFilePaths[0],
				name: 'file',
				success: function (uploadFileRes) {
					uni.hideLoading();
					uploadFileRes = JSON.parse(uploadFileRes.data);
					if(uploadFileRes.code == 200){
						console.log(the_key);
						if(isNumber(the_key)){
							that.imgs[the_key] = uploadFileRes.data;
						}else{
							that[the_key] = uploadFileRes.data;
						}
						
						//console.log(the_key);
					}
				}
			});
			 uploadTask.onProgressUpdate(function (res) {
			  that.percent = res.progress;
			  console.log('上传进度' + res.progress);
			  console.log('已经上传的数据长度' + res.totalBytesSent);
			  console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
			 });
		},
		error : function(e){
			uni.hideLoading();
			console.log(e);
		}
	});
}
//是否为数字
function isNumber(val){
    var regPos = /^\d+(\.\d+)?$/; //非负浮点数
    var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
    if(regPos.test(val) || regNeg.test(val)){
        return true;
    }else{
        return false;
    }
}
//加法函数  
function accAdd(arg1, arg2) {  
    var r1, r2, m;  
    try {  
        r1 = arg1.toString().split(".")[1].length;  
    }  
    catch (e) {  
        r1 = 0;  
    }  
    try {  
        r2 = arg2.toString().split(".")[1].length;  
    }  
    catch (e) {  
        r2 = 0;  
    }  
    m = Math.pow(10, Math.max(r1, r2));  
    return (arg1 * m + arg2 * m) / m;  
}
//减法函数  
function Subtr(arg1, arg2) {  
    var r1, r2, m, n;  
    try {  
        r1 = arg1.toString().split(".")[1].length;  
    }  
    catch (e) {  
        r1 = 0;  
    }  
    try {  
        r2 = arg2.toString().split(".")[1].length;  
    }  
    catch (e) {  
        r2 = 0;  
    }  
    m = Math.pow(10, Math.max(r1, r2));  
     //last modify by deeka  
     //动态控制精度长度  
    n = (r1 >= r2) ? r1 : r2;  
    return ((arg1 * m - arg2 * m) / m).toFixed(n);  
}
//乘法函数
function accMul(arg1, arg2) {  
    var m = 0, s1 = arg1.toString(), s2 = arg2.toString();  
    try {
        m += s1.split(".")[1].length;  
    }  
    catch (e) {  
    }  
    try {  
        m += s2.split(".")[1].length;  
    }  
    catch (e) {  
    }  
    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);  
}
//除法函数  
function accDiv(arg1, arg2) {
    var t1 = 0, t2 = 0, r1, r2;  
    try {  
        t1 = arg1.toString().split(".")[1].length;  
    }
    catch (e) {  
    }  
    try {  
        t2 = arg2.toString().split(".")[1].length;  
    }  
    catch (e) {  
    }  
    //with (Math) {  
        r1 = Number(arg1.toString().replace(".", ""));  
        r2 = Number(arg2.toString().replace(".", ""));  
        return (r1 / r2) * Math.pow(10, t2 - t1);  
    //}  
}
//公共配置缓存更新与读取
/*
key 下标值
value  默认值（取不到值时设定的默认值）
*/
function getCommonStorage(key,value){
	var common_setting = uni.getStorageSync('common_setting');
	if(!common_setting){
		common_setting = {};
		common_setting[key] = value;
		common_setting = JSON.stringify(common_setting);
		uni.setStorageSync('common_setting',common_setting);
		return value;
	}else{
		common_setting = JSON.parse(common_setting);
		if(typeof common_setting[key] == 'undefined' || !common_setting[key]){
			common_setting[key] = value;
			common_setting = JSON.stringify(common_setting);
			uni.setStorageSync('common_setting',common_setting);
			return value;
		}else{
			return common_setting[key];
		}
	}
}
//更新公共配置缓存
function setCommonStorage(key,value){
	var common_setting = uni.getStorageSync('common_setting');
	if(!common_setting){
		common_setting = {};
		common_setting[key] = value;
		common_setting = JSON.stringify(common_setting);
		uni.setStorageSync('common_setting',common_setting);
		return value;
	}else{
		common_setting = JSON.parse(common_setting);
		common_setting[key] = value;
		common_setting = JSON.stringify(common_setting);
		uni.setStorageSync('common_setting',common_setting);
	}
}
var request_tmp = uni.getStorageSync('request_tmp');
if(typeof request_tmp != 'undefined' && request_tmp){
	//config.request_url = request_tmp;
}
//获取定位
function get_location(that,func){
	//获取当前定位
	uni.getLocation({
		//type:'wgs84',
		type:'gcj02', //	真机运行时切换回来
		success:function(res){
			//console.log(res);
			
			that.longitude = res.longitude;
			that.latitude = res.latitude;
			that.circles = [
				{
					latitude:res.latitude,
					longitude: res.longitude,
					color: '#7cb5ec',
					fillColor: '#ffffff00',
					radius:1100,
					strokeWidth: 4
				}
			];
			/*that.covers = [
				{
					latitude:res.latitude,
					longitude: res.longitude,
					width:24,
					height:24,
					iconPath: '/static/images/small_map.png?2'
				}
			]*/
			load_citys(that);
			func();
			
		},
		fail(e) {
			var res = config.address;
			that.longitude = res.longitude;
			that.latitude = res.latitude;
			that.circles = [
				{
					latitude:res.latitude,
					longitude: res.longitude,
					color: '#7cb5ec',
					fillColor: '#ffffff00',
					radius:1100,
					strokeWidth: 4
				}
			];
			load_citys(that);
			func();
			
			uni.showModal({
			      title: '温馨提示',
			      content: '请允许获取您的地理位置，否则将无法正常使用该功能。',
			      showCancel: false,
			      success: function (res) {
			        // 点击确定后，跳转到设置页面，让用户手动打开定位权限
			        uni.openSetting({
			          success: function (res) {
			            // 用户在设置页面同意了定位授权，则执行您的业务逻辑
						load_citys(that);
						func();
			          },
			          fail: function (res) {
			            // 用户在设置页面拒绝了定位授权，则无法使用该功能
			          }
			        });
			      }
			});
			
		}
	});
}
//通过经纬度获取城市信息
function load_citys(that){
	var url = 'https://restapi.amap.com/v3/geocode/regeo?location='+that.longitude+','+that.latitude+'&key='+config.address_key;
	uni.request({
		url:url,
		success: function(res) {
			res = res.data;
			if(res.status != 1){
				that.address = config.address;
			}else{
				that.address = {
					province:res.regeocode.addressComponent.province,
					city:res.regeocode.addressComponent.city,
					district:res.regeocode.addressComponent.district,
					longitude:that.longitude,
					latitude:that.latitude
				}
			}
			var address = JSON.stringify(that.address);
			uni.setStorageSync('address',address);
		},
		fail() {
			that.address = config.address;
			var address = JSON.stringify(that.address);
			uni.setStorageSync('address',address);
		}
	});
}
//获取已保存城市信息
function get_citys(){
	address = uni.getStorageSync('address');
	if(!address){
		return config.address;
	}
	address = JSON.parse(address);
	return address;
}
function caculateTimeago(dateTimeStamp) {
  const minute = 1000 * 60; // 把分，时，天，周，半个月，一个月用毫秒表示

  const hour = minute * 60;
  const day = hour * 24;
  const week = day * 7;
  const now = new Date().getTime(); // 获取当前时间毫秒

  const diffValue = now - dateTimeStamp; // 时间差

  let result = '';

  if (diffValue < 0) {
    return;
  }

  const minC = diffValue / minute; // 计算时间差的分，时，天，周，月

  const hourC = diffValue / hour;
  const dayC = diffValue / day;
  const weekC = diffValue / week;

  if (weekC >= 1 && weekC <= 4) {
    result = ` ${parseInt(weekC, 10)}周前`;
  } else if (dayC >= 1 && dayC <= 6) {
    result = ` ${parseInt(dayC, 10)}天前`;
  } else if (hourC >= 1 && hourC <= 23) {
    result = ` ${parseInt(hourC, 10)}小时前`;
  } else if (minC >= 1 && minC <= 59) {
    result = ` ${parseInt(minC, 10)}分钟前`;
  } else if (diffValue >= 0 && diffValue <= minute) {
    result = '刚刚';
  } else {
    const datetime = new Date();
    datetime.setTime(dateTimeStamp);
    const Nyear = datetime.getFullYear();
    const Nmonth = datetime.getMonth() + 1 < 10 ? `0${datetime.getMonth() + 1}` : datetime.getMonth() + 1;
    const Ndate = datetime.getDate() < 10 ? `0${datetime.getDate()}` : datetime.getDate();
    result = `${Nyear}-${Nmonth}-${Ndate}`;
  }

  return result;
}
module.exports = {
	config:config,
	get_access_token,
	common_if_login,
	load_common_list,
	reset_list,
	upload_file,
	calert,
	accAdd,
	Subtr,
	accMul,
	accDiv,
	load_msg,
	getCommonStorage,
	setCommonStorage,
	get_location,
	get_citys,
	caculateTimeago:caculateTimeago
}